package com.cadre.web.controller.officer;

import com.alibaba.fastjson.JSON;
import com.cadre.common.utils.R;
import com.cadre.common.utils.SecurityUtils;
import com.cadre.common.utils.annotation.SysLog;
import com.cadre.common.utils.common.GenerateUUID;
import com.cadre.common.utils.common.HttpContextUtils;
import com.cadre.common.utils.common.IPUtils;
import com.cadre.common.utils.oldutil.*;
import com.cadre.system.domain.officer.*;
import com.cadre.system.service.A01Service;
import com.cadre.system.service.PersonService;
import com.cadre.system.service.SysConfigService;
import com.cadre.system.service.SysLogService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import com.cadre.system.service.PX_PXBXXService;
import com.cadre.system.service.PX_PXBXX_DETAILService;
import com.cadre.system.service.PX_JGXXService;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

@Api(tags = {"培训接口"})
@RequestMapping({"/profess/PX_PXBXX"})
@RestController
public class PX_PXBXXController {
    @Resource
    private PX_PXBXXService PX_PXBXXService;
    @Resource
    private PersonService personService;
    @Resource
    private A01Service a01Service;
    @Resource
    private PX_PXBXX_DETAILService PX_PXBXX_DETAILService;
    @Resource
    private SysLogService sysLogService;
    @Resource
    private PX_JGXXService PX_JGXXService;
    @Resource
    private SysConfigService sysConfigService;
    @Value("${ModelFilePath}")
    private String ModelFilePath;

    @RequestMapping(value = {"/list"}, method = {RequestMethod.POST})
    @ApiOperation("人员列表")
    public R list(@RequestParam Map<String, Object> map) {
        return R.ok().put("page", (Object) this.PX_PXBXXService.selectList(map));
    }

    @GetMapping({"/listByPersonid/{personId}"})
    @ApiOperation("根据人员查询培训信息")
    public R list(@PathVariable String personId) {
        Map<String, Object> cxMap = new HashMap<>();
        cxMap.put("personid", personId);
        return R.ok().put("data", (Object) this.PX_PXBXXService.selectListByPersonid(cxMap));
    }

    @GetMapping({"/info/{flowId}"})
    @ApiOperation("获取信息")
    public R info(@PathVariable("flowId") String flowId) {
        PX_PXBXX PX_PXBXX = (PX_PXBXX) this.PX_PXBXXService.getById(flowId);
        Map<String, Object> map = new HashMap<>();
        map.put("pxbcode", flowId);
        List<PX_PXBXX_DETAIL> list = this.PX_PXBXX_DETAILService.selectByAll(map);
        Map<String, Object> map1 = new HashMap<>();
        List<A01> list2 = null;
        if (list.size() > 0) {
            String[] ids = new String[list.size()];
            for (int i = 0; i < list.size(); i++) {
                ids[i] = list.get(i).getPersonid();
            }
            map1.put("flowids", ids);
            list2 = this.a01Service.selectList(map1);
        }
        return R.ok().put("data", (Object) PX_PXBXX).put("list", (Object) list2);
    }

    @GetMapping({"/detail"})
    public R detail(String flowId, Integer pageNum, Integer pageSize) {
        Map<String, Object> map1 = new HashMap<>();
        map1.put("pxbcode", flowId);
        List<PX_PXBXX_DETAIL> list = this.PX_PXBXX_DETAILService.selectByAll(map1);
        Map<String, Object> map = new HashMap<>();
        map.put("pageNum", pageNum);
        map.put("pageSize", pageSize);
        if (list.size() > 0) {
            String[] ids = new String[list.size()];
            for (int i = 0; i < list.size(); i++) {
                ids[i] = list.get(i).getPersonid();
            }
            map.put("flowids", ids);
        }
        return R.ok().put("page", (Object) this.personService.selectList(map));
    }

    @PostMapping({"/save"})
    public R save(@RequestBody PX_PXBXX PX_PXBXX) {
        PX_PXBXX.setPxbcode(GenerateUUID.getUUID());
        this.PX_PXBXXService.save(PX_PXBXX);
        return R.ok();
    }

    @PostMapping({"/saveList"})
    public R saveList(@RequestBody List<PX_PXBXX> PX_PXBXXs) {
        if (PX_PXBXXs.size() > 0) {
            for (int i = 0; i < PX_PXBXXs.size(); i++) {
                new PX_PXBXX().setPxbcode(GenerateUUID.getUUID());
                this.PX_PXBXXService.save(PX_PXBXXs.get(i));
            }
        }
        return R.ok();
    }

    @PostMapping({"/saveDList"})
    @Transactional
    @ApiOperation("保存培训班信息")
    public R saveDList(@RequestBody PX_PXBXX entity) {
        String uuid = GenerateUUID.getUUID();
        entity.setPxbcode(uuid);
        if (!this.PX_PXBXXService.save(entity)) {
            return R.error();
        }
        for (String personid : entity.getPersonids()) {
            PX_PXBXX_DETAIL px_PXBXX_DETAIL = new PX_PXBXX_DETAIL();
            px_PXBXX_DETAIL.setFlowid(GenerateUUID.getUUID());
            px_PXBXX_DETAIL.setPxbcode(uuid);
            px_PXBXX_DETAIL.setPersonid(personid);
            this.PX_PXBXX_DETAILService.save(px_PXBXX_DETAIL);
        }
        try {
            PX_PXBXX pxold = new PX_PXBXX();
            SysLogEntity sysLog = new SysLogEntity();
            sysLog.setOperation("保存培训信息");
            sysLog.setOperationtable("PX_PXBXX");
            sysLog.setOperationset("PX_PXBXX");
            sysLog.setParams(JSON.toJSONString(entity).toLowerCase());
            sysLog.setOperationtype(0);
            sysLog.setOldparams(JSON.toJSONString(pxold).toLowerCase());
            sysLog.setMethod("saveDList");
            sysLog.setTargetid("");
            sysLog.setIp(IPUtils.getIpAddr(HttpContextUtils.getHttpServletRequest()));
            sysLog.setUsername(SecurityUtils.getUsername());
            sysLog.setTime(100L);
            sysLog.setCreateDate(new Date());
            this.sysLogService.save(sysLog);
        } catch (Exception e) {
        }
        return R.ok();
    }

    @PostMapping({"/updateDList"})
    @Transactional
    @ApiOperation("修改培训班信息")
    public R updateDList(@RequestBody PX_PXBXX entity) {
        if (!this.PX_PXBXXService.updateById(entity)) {
            return R.error();
        }
        if (entity.getPersonids().size() != 0) {
            this.PX_PXBXX_DETAILService.deleteByPxb(entity.getPxbcode());
            for (String personid : entity.getPersonids()) {
                PX_PXBXX_DETAIL px_PXBXX_DETAIL = new PX_PXBXX_DETAIL();
                px_PXBXX_DETAIL.setFlowid(GenerateUUID.getUUID());
                px_PXBXX_DETAIL.setPxbcode(entity.getPxbcode());
                px_PXBXX_DETAIL.setPersonid(personid);
                this.PX_PXBXX_DETAILService.save(px_PXBXX_DETAIL);
            }
        } else {
            this.PX_PXBXX_DETAILService.deleteByPxb(entity.getPxbcode());
        }
        try {
            PX_PXBXX pxold = (PX_PXBXX) this.PX_PXBXXService.getById(entity.getPxbcode());
            SysLogEntity sysLog = new SysLogEntity();
            sysLog.setOperation("修改培训信息");
            sysLog.setOperationtable("PX_PXBXX");
            sysLog.setOperationset("PX_PXBXX");
            sysLog.setParams(JSON.toJSONString(entity).toLowerCase());
            sysLog.setOperationtype(1);
            sysLog.setOldparams(JSON.toJSONString(pxold).toLowerCase());
            sysLog.setMethod("updateDList");
            sysLog.setTargetid("");
            sysLog.setIp(IPUtils.getIpAddr(HttpContextUtils.getHttpServletRequest()));
            sysLog.setUsername(SecurityUtils.getUsername());
            sysLog.setTime(100L);
            sysLog.setCreateDate(new Date());
            this.sysLogService.save(sysLog);
        } catch (Exception e) {
        }
        return R.ok();
    }

    @PostMapping({"/update"})
    public R update(@RequestBody PX_PXBXX PX_PXBXX) {
        ValidatorUtils.validateEntity(PX_PXBXX, new Class[0]);
        this.PX_PXBXXService.updateById(PX_PXBXX);
        return R.ok();
    }

    @PostMapping({"/updateList"})
    public R updateList(@RequestBody List<PX_PXBXX> entityList) {
        this.PX_PXBXXService.updateBatchById(entityList);
        return R.ok();
    }

    @PostMapping({"/delete"})
    @SysLog(value = "删除培训信息", target = "PX_PXBXX", set = "PX_PXBXX", type = DateUtil.SUB_MONTH)
    @ApiOperation("删")
    public R delete(@RequestBody String[] flowIds) {
        if (flowIds.length == 0) {
            return R.error();
        }
        this.PX_PXBXXService.removeBatchByIds(Arrays.asList(flowIds));
        for (String str : flowIds) {
            this.PX_PXBXX_DETAILService.deleteByPxb(str);
        }
        return R.ok();
    }

    @GetMapping({"/treeinit"})
    @ApiOperation("名册树")
    public List<Tree> treeInit() {
        List<Tree> TreeList = this.PX_PXBXXService.treeInit(SecurityUtils.getUserId().toString());
        for (Tree tree : TreeList) {
            if (tree.getPid() == null || "".equals(tree.getPid())) {
                tree.setOpen(true);
                tree.setParent(true);
                tree.setPid("0");
            }
        }
        return TreeList;
    }

    @PostMapping({"/personinit"})
    @ApiImplicitParam(name = "nameListId", value = "名册Id", required = true, paramType = "query", defaultValue = "1")
    @ApiOperation("干部名册：自定义名册列表")
    @ResponseBody
    public ResultVO selectPersonListById(String nameListId) {
        try {
            return this.PX_PXBXXService.selectPersonListById(nameListId);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultVOUtil.error(ResultEnum.ERROR);
        }
    }

    @PostMapping({"/saveNameList"})
    @Transactional
    @ApiOperation("保存名册")
    public R saveNameList(@RequestBody PX_PXBXX entity) {
        entity.setPxbcode(GenerateUUID.getUUID());
        if (this.PX_PXBXXService.save(entity)) {
            return R.ok();
        }
        return R.error();
    }

    @PostMapping({"/updateName"})
    @ApiOperation("修改名册名称")
    public R updateName(@RequestBody Map<String, Object> map) {
        this.PX_PXBXXService.updateNameById(String.valueOf(map.get("flowid")), String.valueOf(map.get("newName")));
        return R.ok();
    }

    @PostMapping({"/deleteNameList"})
    @SysLog(value = "删除名册信息", target = "PX_PXBXX", set = "PX_PXBXX", type = DateUtil.SUB_MONTH)
    @ApiOperation("删")
    public R deleteNameList(@RequestBody String[] ids) {
        if (ids.length == 0) {
            return R.error();
        }
        this.PX_PXBXXService.removeBatchByIds(Arrays.asList(ids));
        for (String str : ids) {
            this.PX_PXBXX_DETAILService.deleteByPxb(str);
        }
        return R.ok();
    }

    @PostMapping({"/addPersonToNameList"})
    @ApiOperation("添加人员到名册")
    public R addPersonToNameList(@RequestBody Map<String, Object> map) {
        ArrayList<Object> personIds = new ArrayList<>();
        personIds.addAll((Collection) map.get("personIds"));
        for (int i = 0; i < personIds.size(); i++) {
            try {
                PX_PXBXX_DETAIL ppd = new PX_PXBXX_DETAIL();
                ppd.setFlowid(GenerateUUID.getUUID());
                ppd.setPxbcode(String.valueOf(map.get("nameListId")));
                ppd.setPersonid(String.valueOf(personIds.get(i)));
                ppd.setUnitid(String.valueOf(i));
                this.PX_PXBXX_DETAILService.save(ppd);
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
        return R.ok();
    }

    @PostMapping({"/DeletePersonFromNameList"})
    @SysLog(value = "删除名册人员信息", target = "PX_PXBXX", set = "PX_PXBXX", type = DateUtil.SUB_MONTH)
    @ApiOperation("从名册中删除人员")
    public R deletePerson(@RequestBody Map<String, Object> map) {
        ArrayList<Object> personIds = new ArrayList<>();
        personIds.addAll((Collection) map.get("personIds"));
        String nameListId = String.valueOf(map.get("nameListId"));
        String[] ids = new String[personIds.size()];
        for (int i = 0; i < personIds.size(); i++) {
            ids[i] = String.valueOf(personIds.get(i));
        }
        this.PX_PXBXX_DETAILService.deletePerson(nameListId, ids);
        return R.ok();
    }

    @PostMapping({"/saveModelInfo"})
    @ResponseBody
    public R save(@RequestParam String jgname, @RequestParam String remark, @RequestParam String configListJSON, @RequestParam("file") MultipartFile file, HttpServletRequest request, HttpServletResponse response) {
        PX_JGXX pX_JGXX = new PX_JGXX();
        pX_JGXX.setJgname(jgname);
        pX_JGXX.setRemark(remark);
        pX_JGXX.setConfigList(JSON.parseArray(configListJSON, SysConfigEntity.class));
        pX_JGXX.setJgcode(new SimpleDateFormat("yyyyMMddHHmmssS").format(new Date()));
        this.PX_JGXXService.save(pX_JGXX);
        if (pX_JGXX.getConfigList() != null && pX_JGXX.getConfigList().size() > 0) {
            for (int j = 0; j < pX_JGXX.getConfigList().size(); j++) {
                pX_JGXX.getConfigList().get(j).setId(null);
                pX_JGXX.getConfigList().get(j).setRemark("报表模版_" + pX_JGXX.getJgcode());
                pX_JGXX.getConfigList().get(j).setStatus(0);
                this.sysConfigService.save(pX_JGXX.getConfigList().get(j));
            }
        }
        File baseDir = new File(this.ModelFilePath);
        if (!baseDir.exists()) {
            baseDir.mkdirs();
        }
        System.out.println("上传报表模版>>>>>>>>>>>>>>>>>>>>" + baseDir.getAbsolutePath());
        try {
            FileUtils.copyInputStreamToFile(file.getInputStream(), new File(baseDir.getAbsolutePath(), File.separator + (pX_JGXX.getJgcode() + ".xlsx")));
        } catch (IOException e) {
            e.printStackTrace();
            System.err.println(e.getMessage());
        }
        return R.ok();
    }

    @PostMapping({"/deleteModelInfo"})
    @SysLog(value = "删除报表模版信息", target = "PX_JGXX", set = "PX_JGXX", type = DateUtil.SUB_MONTH)
    @ApiOperation("删")
    public R deleteModelInfo(@RequestBody String[] ids) {
        if (ids.length == 0) {
            return R.error();
        }
        this.PX_JGXXService.removeBatchByIds(Arrays.asList(ids));
        for (int i = 0; i < ids.length; i++) {
            List<Long> idList = new ArrayList<>();
            List<SysConfigEntity> list = this.sysConfigService.queryModelInfoConfigs(ids[i]);
            for (int j = 0; j < list.size(); j++) {
                idList.add(list.get(j).getId());
            }
            try {
                this.sysConfigService.deleteBatch((Long[]) idList.toArray(new Long[idList.size()]));
            } catch (Exception e) {
            }
            try {
                File fileDel = new File(this.ModelFilePath + ids[i] + ".xlsx");
                if (fileDel.exists()) {
                    if (fileDel.delete()) {
                        System.out.println("Deleted the file: " + fileDel.getName());
                    } else {
                        System.out.println("Failed to delete the file.");
                    }
                }
            } catch (Exception e2) {
            }
        }
        return R.ok();
    }

    @RequestMapping(value = {"/getModelInfos"}, method = {RequestMethod.POST})
    @ApiOperation("报表模版列表")
    public R getModelInfos(@RequestParam Map<String, Object> map) {
        List<PX_JGXX> list = this.PX_JGXXService.getModelInfos(map);
        for (int i = 0; i < list.size(); i++) {
            list.get(i).setFilepath(this.ModelFilePath + list.get(i).getJgcode() + ".xlsx");
        }
        return R.ok().put("data", (Object) list);
    }
}
